**Program for calculating Imben's matching estimator
**kta, version 1.3 02/21/05
**Syntax: matchcalc depvar treatment weight [if] [in][, indexfilename()]

program define matchcalc
version 8.0

syntax varlist (min=3 max=3) [if] [in] [, id(varname numeric) index(string) exact(real 0) matches(varname numeric)]
tempvar touse
marksample touse


tokenize `varlist'
local v `1'
local tg `2'
local w `3'

quietly {

	count if `tg'==1
	local nttot=r(N)

	preserve
	if `"`if'"'~="" | "`in'"~="" {
		keep `if' `in'
	}

	if `exact'==1 {
		drop if `matches'==0
		count if `tg'==1
		local nttot=r(N)
	}

	*Calculate ATT
	capture gen _wyi=(`tg' - (1-`tg')*`w')*`v'
	sum _wyi
	local d=r(sum)
	local att=`d'/`nttot'

	*Abadie and Imbens ses
	use `index', clear
	capture drop __*
	drop if `id'==.
	drop if tid==.
	egen Jm=count(tid), by(tid)
	gen vdif=((v1-v0-`att')^2)/Jm
	collapse (sum) vdif, by(tid)
	sum vdif
	local s2=(r(sum))/(2*`nttot')
	restore

	preserve
	if `"`if'"'~="" | "`in'"~="" {
		keep `if' `in'
	}

	if `exact'==1 {
		count if `tg'==1
		local tn=r(N)
		drop if `matches'==0
	}

	cap gen var_ti=(`tg' - (1-`tg')*`w')^2*`s2'
	sum var_ti
	local var_t=(r(sum))/`nttot'^2

	*Becker & Ichino ses 
	sum `v' if `matches'==1 & `tg'==1
	local vy1=r(Var)/`nttot'
	sum `v' if `matches'==1 & `tg'==0
	local vy0=r(Var)
	gen _w2=(`w'^2)*`vy0'
	sum _w2 if `matches'==1 & `tg'==0
	local vyc=r(sum)/(`nttot'^2)
	local bivar_t=`vy1'+`vyc'
	restore
	
	local se=sqrt(`var_t')
	local sebi=sqrt(`bivar_t')
	local t=`att'/`se'
	local tbi=`att'/`sebi'
	
	if `exact'==1 {
		local pm=(`nttot'/`tn')*100
		count if `tg'==0 & `w'~=0
		local cm=r(N)
		local tm=`nttot'
	}	
	
	else {
	count if `tg'==1 & `w'~=0
	local tm=r(N)
	local pm=(`tm'/`nttot')*100
	count if `tg'==0 & `w'~=0
	local cm=r(N)
	}
}



	di _newline(3) _column(1) as result "ATT estimation using Abadie & Imbens Method"
	di _newline(4) _column(35) as result "N matched treated: " `tm'
	di		   _column(35) as result "N matched control: " `cm'
	di 		   _column(35) as result "% treated matched: " `pm'
	di as text "{hline 57}" 
	di _newline(1) 	_column(5) as text "ATT" ///
				_column(20) as text "s.e." /// 						
				_column(35) as text "t-statistic" 
	di as text "{hline 57}"
	di _newline(1) 	_column(5) as result `att'    ///
				_column(20) as result `se'  ///
				_column(35) as result `t' 
	di as text "{hline 57}"
	di as text "Becker & Ichino s.e. = " as result `sebi'
	di as text "t-statistic = " as result `tbi'

end
